var express = require('express');
let { accountNumberModel } = require('../model/model_ylx');
var router = express.Router();
const bcrypt = require('bcrypt');
const jwt = require('jsonwebtoken')
const tencentcloud = require("tencentcloud-sdk-nodejs-sms");
const { verifyToken } = require('../verifyToken');


// 注册
router.post('/regist', async (req, res) => {
  let registInfo = req.body
  let newRegistInfo = {
    phone: registInfo.phone,
    password: registInfo.password
  }
  let code = registInfo.code
  let accountNumber = await accountNumberModel.find({ phone: newRegistInfo.phone }).exec()
  if (accountNumber.length === 0) {
    // 生成salt
    const saltRounds = 10;
    //saltRounds的值指定了生成salt的轮数。轮数越高，生成salt的时间越长，从而增加了对抗暴力破解的难度。
    const salt = bcrypt.genSaltSync(saltRounds);
    const saferegistInfo = { ...newRegistInfo, password: bcrypt.hashSync(newRegistInfo.password, salt) }
    if (code === testCode) {
      await accountNumberModel.create(saferegistInfo)
      testCode = ''
      res.send({ code: 200, msg: '注册成功~' })
    } else {
      res.send({ code: 302, msg: '验证码不正确~' })
    }
  } else {
    res.send({ code: 301, msg: '该账号已注册，若忘记密码，请跳转"忘记密码"~' })
  }
})

router.post('/login', async (req, res) => {
  let accountNumberInfo = req.body
  let phone = accountNumberInfo.phone
  let password = accountNumberInfo.password
  let accountNumber = await accountNumberModel.find({ phone }).exec()
  if (accountNumber.length !== 0) {
    // 获取保存在数据库中的加密密码和用户输入的密码
    const savedDataBasePassword = accountNumber[0].password;
    // 验证密码
    const isPasswordValid = bcrypt.compareSync(password, savedDataBasePassword);
    // 匹配数据库中的加密密码是否和输入密码一致
    switch (isPasswordValid) {
      case true:
        // 是否已登录
        switch (accountNumber[0].isLogin) {
          case true:
            res.send({ code: 302, msg: '请更换账号，该账号已登录~' })
            break;
          default:
            await accountNumberModel.updateOne({ phone }, { isLogin: true })
            testCode = ''
            let access_token = jwt.sign(accountNumberInfo, 'keyword', { expiresIn: '10s' })
            let refresh_token = jwt.sign(accountNumberInfo, 'keyword', { expiresIn: '30s' })
            res.send({ code: 200, msg: '登陆成功', access_token, refresh_token })
            break;
        }
        break;
      default:
        res.send({ code: 301, msg: '账号或密码不正确' })
        break;
    }
  } else {
    res.send({ code: 303, msg: '用户不存在' })
  }
})


router.post('/loginbyphone', async (req, res) => {
  let { phone, code } = req.body
  let data = await accountNumberModel.find({ phone }).exec()
  if (data.length !== 0) {
    if (data[0].isLogin === true) {
      res.send({ code: 301, msg: '该用户已登录' })
      return false
    } else {
      if (code === testCode) {
        await accountNumberModel.updateOne({ phone }, { isLogin: true })
        testCode = ''
        let access_token = jwt.sign(req.body, 'keyword', { expiresIn: '10s' })
        let refresh_token = jwt.sign(req.body, 'keyword', { expiresIn: '30s' })
        res.send({ code: 200, msg: '登陆成功', access_token, refresh_token })
      } else {
        res.send({ code: 302, msg: '验证码不正确~' })
      }
    }
  }
})





router.post('/refreshtoken', (req, res) => {
  let access_token = jwt.sign(req.body, 'keyword', { expiresIn: '10s' })
  res.send({
    code: 200, access_token
  })
})

router.get('/getusers', async (req, res) => {
  let verifyRes = verifyToken(req)
  let data
  if (verifyRes.code === 200) {
    data = await accountNumberModel.find().exec()
    res.send({ coed: 200, data })
  } else {
    res.send(verifyRes)
  }
})



let testCode
function createCode() {
  //数字验证码
  testCode = String(Math.floor(Math.random() * 1000000)).padEnd(6, 0);
}
// 发送短信验证码
router.post('/sendcode', async (req, res) => {
  let { phone, action } = req.body
  //调用创建code方法
  createCode()
  const SmsClient = tencentcloud.sms.v20210111.Client;
  // 设置短信密钥
  const clientConfig = {
    credential: {
      secretId: "AKIDutkUI6xgRlEaorhKn25ywnZThipmdvaB",
      secretKey: "UnwrdDdXVKQWvCNM8vcFrPp8HNQK6hDU",
    },
    region: "ap-beijing",
    profile: {
      httpProfile: {
        endpoint: "sms.tencentcloudapi.com",
      },
    },
  };
  // 实例化要请求产品的client对象,clientProfile是可选的
  const client = new SmsClient(clientConfig);
  //设置短信参数
  const params = {
    "PhoneNumberSet": [
      "+86" + phone
    ],
    "SmsSdkAppId": "1400852890",
    "SignName": "一个鹏的公众号",
    "TemplateId": "1937785",
    "TemplateParamSet": [
      testCode
    ]
  };

  switch (action) {
    case 'login':
      let data = await accountNumberModel.find({ phone }).exec()
      if (data.length !== 0) {
        client.SendSms(params).then(
          (data) => {
            console.log(data);
            res.send({
              createTime: new Date().getTime(),
              testCode
            })
          },
          (err) => {
            console.error("error", err);
          }
        );
      } else {
        res.send({ code: 301, msg: '该用户未注册~' })
      }
      break;
    case 'register':
      client.SendSms(params).then(
        (data) => {
          console.log(data);
          res.send({
            createTime: new Date().getTime(),
            testCode
          })
        },
        (err) => {
          console.error("error", err);
        }
      );
      break
    default:
      break;
  }
})



router.post('/testsend', async (req, res) => {
  createCode()
  switch (req.body.action) {
    case 'login':
      let data = await accountNumberModel.find({ phone: req.body.phone }).count()
      if (data !== 0) {
        res.send({ testCode: 132, testCode })
      } else {
        res.send({ code: 301, msg: '该用户未注册~' })
      }
      break;
    case 'register':
      res.send({ testCode: 132, testCode })
      break

    default:
      break;
  }
})


module.exports = router;
